<template>
    <view class="address-container">
		<!-- 骨架屏区域开始 -->
		<uv-skeletons :loading="isShowSkeleton" :skeleton="skeleton"></uv-skeletons>
		<!-- 骨架屏区域结束 -->

        <!-- 地址列表区域开始 -->
        <view class="address-item" v-for="(item, index) in userAddrList" :key="index">
            <view class="left">
                <text class="icon iconfont icon-dizhi"></text>
            </view>
            <view class="middle">
                <view class="top">
                    <view class="top-left">{{item.name}} {{item.mobile}}</view>
                    <view class="top-right" v-if="item.is_default == 1">
                        <text class="txt">默认</text>
                    </view>
                </view>
                <view class="bottom">
                    <text>{{item.region}} {{ item.address }}</text>
                </view>
            </view>
            <view class="right">
                <text class="icon iconfont icon-bianji" @click="showEditDeliveryAddr(item)"></text>
                <text class="icon iconfont icon-shanchu" @click="deleteDeliveryAddress(item)"></text>
            </view>
        </view>
		<!-- 地址列表区域结束 -->

        <!-- 新增地址按钮区域 -->
        <view class="address-btn-wrap">
            <button
                class="address-btn"
                hover-class="button-hover"
                @click="showAddDeliveryAddr"
            >
            + 新增地址
            </button>
        </view>

        <!-- 编辑收货地址弹层 -->
		<uni-popup ref="deliveryAddrPopup" background-color='#fff' :mask-click="false">
			<view class="delivery-addr">
				<!-- 基础表单校验 -->
				<uni-forms ref="formRef" :rules="rules" :modelValue="formData">
					<!-- 收货人 -->
					<uni-forms-item :label-width="labelWidth" label="收货人" required name="name">
						<uni-easyinput  :styles="styles" :placeholderStyle="placeholderStyle" v-model="formData.name" placeholder="请输入收货人" />
					</uni-forms-item>
					
					<!-- 手机号 -->
					<uni-forms-item :label-width="labelWidth" label="手机号" required name="mobile">
						<uni-easyinput type="number" :styles="styles" :maxlength="11" :placeholderStyle="placeholderStyle" v-model="formData.mobile" placeholder="请输入手机号" />
					</uni-forms-item>
					
					<!-- 是否默认 -->
					<uni-forms-item :label-width="labelWidth" label="是否默认">
						<uni-data-checkbox selectedColor="#008000" selectedTextColor="#008000" v-model="formData.is_default" :localdata="isDefaults" />
					</uni-forms-item>
					
					<!-- 地区 -->
					<uni-forms-item :label-width="labelWidth" label="地区" required name="region">
						<view class="region-box">
							<!-- 省份 -->
							<uni-data-select
								v-model="formData.province_id"
								:localdata="provinces"
								placeholder="请选择省"
								@change="changeProvince"
								:clear="false"
                                class="region-item"
							/>
								
							<!-- 城市 -->
							<uni-data-select
								v-model="formData.city_id"
								:localdata="cities"
								placeholder="请选择市"
								@change="changeCity"
								:clear="false"
                                class="region-item"
							/>
								
							<!-- 区 -->
							<uni-data-select
								v-model="formData.district_id"
								:localdata="districts"
								placeholder="请选择区"
								@change="changeDistrict"
								:clear="false"
                                class="region-item"
							/>
						</view>
					</uni-forms-item>
					
					<!-- 详细地址 -->
					<uni-forms-item :label-width="labelWidth" label="地址" required name="address">
						<uni-easyinput type="textarea" v-model="formData.address" placeholder="请输入详细地址" />
					</uni-forms-item>
				</uni-forms>
			</view>
			<view class="delivery-addr-btn-box">
				<button @click="closeDeliveryAddr" size="mini" class="delivery-addr-btn">关闭</button>
				<button type="primary" style="background-color: #008000;" @click="confirmDeliveryAddr" size="mini" class="delivery-addr-btn">确定</button>
			</view>
		</uni-popup>
    </view>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue"
import {reqAddUserDeliveryAddrAPI, reqDeleteUserDeliveryAddrAPI, reqEditUserDeliveryAddrAPI, reqUserDeliveryAddrListAPI} from '../../apis/userDeliveryAddr'
import {reqRegionListAPI} from '../../apis/region'
import { useUserStore } from "../../stores";
import { onLoad } from "@dcloudio/uni-app";

const userStore = useUserStore()

// --------------- 定义骨架变量开始 ---------------
// 定义是否显示骨架
const isShowSkeleton = ref(false)

// 定义骨架参数
const skeleton = reactive([
    {
        type: 'flex',
        num: 7,
        style: 'align-items: center;background-color: #fff;padding:20rpx;border-radius: 6rpx;',
        children: [
            {
                type: 'custom',
                num: 1,
                style: 'width: 60rpx;height:80rpx;margin-right: 10rpx'
            },
            {
                type: 'custom',
                num: 2,
                style: ['width: 300rpx;height:40rpx;', 'width: 480rpx;height:30rpx;']
            },
			{
                type: 'custom',
                num: 1,
                style: 'width: 50rpx;height:50rpx;margin: 0 10rpx'
            },
			{
                type: 'custom',
                num: 1,
                style: 'width: 50rpx;height:50rpx;margin-left: 30rpx'
            },
        ]
    },
	20
])
// --------------- 定义骨架变量结束 ---------------



// ------------- 收货地址列表功能开始 -------------
// 定义用户收货地址数据
const userAddrList:any = ref([])

onLoad(() => {
	getUserAddrList()
})

// 获取用户收货地址
const getUserAddrList = async () => {
	// 显示骨架
    isShowSkeleton.value = true

	// 请求用户收货地址数据
	const result:any = await reqUserDeliveryAddrListAPI({status: 1})
  	userAddrList.value = result.data.user_delivery_addrs != null ? result.data.user_delivery_addrs : []

	// 隐藏骨架
    isShowSkeleton.value = false
}
// ------------- 收货地址列表功能结束 -------------



// ------------- 新增收货地址功能开始 -------------
const opt = ref('add')

// 显示新增收货地址
const showAddDeliveryAddr = async () => {
	opt.value = 'add'
	
	// 重置表单
	formData.id = 0
	formData.name = ''
	formData.mobile = ''
	formData.is_default = 0
	formData.province_id = 0
	formData.city_id = 0
	formData.district_id = 0
	formData.region = ''
	formData.address = ''
	
	cities.value = []
	districts.value = []
	
	// 获取省份数据
	await getProvinceList()
	deliveryAddrPopup.value.open('top')
}

// ------------- 新增收货地址功能结束 -------------



// ------------- 编辑收货地址功能开始 -------------
const deliveryAddrPopup = ref()

const labelWidth:any = ref('75px')

// 定义省份数据
const provinces = ref([])

// 定义市数据
const cities = ref([])

// 定义区数据
const districts = ref([])

const isDefaults = ref([
	{
		text: '否',
		value: 0
	},
	{
		text: '是',
		value: 1
	},
])

// 提交数据
const formData:any = reactive({
	id: 0,
	name: '',
	mobile: '',
	province_id: 0,
	city_id: 0,
	district_id: 0,
	region: '',
	address: '',
	is_default: 0
})

const formRef = ref()

// 验证规则
const rules = {
	name: {
		rules: [{
			required: true,
			errorMessage: '收货人不能为空!'
		}]
	},
	mobile: {
		rules: [
			{
				required: true,
				errorMessage: '手机号不能为空!'
			},
			{
				validateFunction: function(rule:any, value:any, data:any, callback:any) {
					let reg = /^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\d{8}$/
					if (!reg.test(value)) {
						callback('请输入正确格式的手机号!')
					}
					return true
				}
			}
		]
	},
	region: {
		rules: [
			{
				required: true,
				errorMessage: '请选择地区!'
			},
			{
				validateFunction: function(rule:any, value:any, data:any, callback:any) {
					if (formData.province_id == 0 || formData.city_id == 0 || formData.district_id == 0) {
						callback('请选择地区!')
					}
					return true
				}
			}
		]
	},
	address: {
		rules: [
			{
				required: true,
				errorMessage: '详细地址不能为空!'
			}
		]
	}
}
// 输入框样式
const styles = ref(
	// {
	// 	color: '#FAE0DB',
	// 	borderColor: '#FAE0DB',
	// }
)
// 提示样式
const placeholderStyle = ref('font-size:14px')

// 显示编辑收货地址
const showEditDeliveryAddr = async (item:any) => {
	opt.value = 'edit'
	// 获取省份数据、获取城市数据、获取区县数据
	await Promise.all([
		getProvinceList(), 
		getCityList(item.province_id), 
		getDistrictList(item.city_id)
	])

	// 赋值表单
	formData.id = item.id
	formData.name = item.name
	formData.mobile = item.mobile
	formData.is_default = item.is_default
	formData.province_id = item.province_id
	formData.city_id = item.city_id
	formData.district_id = item.district_id
	formData.region = item.region
	formData.address = item.address
	
	deliveryAddrPopup.value.open('top')
}

// 确认保存收货地址
const confirmDeliveryAddr = () => {
	formRef.value.validate().then(async () => {
		let result:any = null
		if (opt.value == 'add') {
			result = await reqAddUserDeliveryAddrAPI(formData)
		} else {
			result = await reqEditUserDeliveryAddrAPI(formData)
		}
		
		// 判断当前收货地址是否默认,如果默认则需要将其他地址修改为非默认
		if (formData.is_default == 1) {
			userAddrList.value.forEach((item:any) => {
				item.is_default = 0
			})
		}
		
		if (opt.value == 'add') {
			formData.id = result.data.id
			// 必须使用深拷贝，否则点击编辑的时候重新给formData赋值的时候也会修改新增的收货地址
			userAddrList.value.unshift(JSON.parse(JSON.stringify(formData)))
		} else {
			// 更新列表数据
			const deliveryAddr = userAddrList.value.find((item:any) => item.id == formData.id)
			for (const key in formData) {
				deliveryAddr[key] = formData[key]
			}
		}
		
		uni.showToast({
			title: '编辑地址成功',
			duration: 1000
		})

		// 如果是默认地址，添加到 pinia 
		if (formData.is_default == 1) {
			userStore.setDeliveryAddr({
				id: formData.id,
				name: formData.name,
				mobile: formData.mobile,
				province_id: formData.province_id,
				city_id: formData.city_id,
				district_id: formData.district_id,
				region: formData.region,
				address: formData.address,
				is_default: formData.is_default
			})
		}
		
		deliveryAddrPopup.value.close()
	}).catch(() => {
		// console.log('err =', err);
	})
}

// 关闭收货地址选择弹层
const closeDeliveryAddr = () => {
	deliveryAddrPopup.value.close()
}

// 获取省份数据
const getProvinceList = async () => {
	const result:any = await reqRegionListAPI({pid: 0})
	provinces.value = []
	const provinceList = result.data.regions != null ? result.data.regions : []
	provinceList.forEach((item:any) => {
		provinces.value.push({
			value: item.id,
			text: item.name
		} as never)
	})
	
	provinces.value.unshift({
		value: 0,
		text: '请选择省'
	} as never)
	
	return 'ok'
}

// 获取市数据
const getCityList = async (pid:any) => {
	const result:any = await reqRegionListAPI({pid})
	
	cities.value = []
	const cityList = result.data.regions != null ? result.data.regions : []
	cityList.forEach((item:any) => {
		cities.value.push({
			value: item.id,
			text: item.name
		} as never)
	})
	
	cities.value.unshift({
		value: 0,
		text: '请选择市'
	} as never)
	
	return 'ok'
}

// 获取区县数据
const getDistrictList = async (pid:any) => {
	const result:any = await reqRegionListAPI({pid})
	
	districts.value = []
	const districtList = result.data.regions != null ? result.data.regions : []
	districtList.forEach((item:any) => {
		districts.value.push({
			value: item.id,
			text: item.name
		} as never)
	})
	
	return 'ok'
}

// 选择省份
const changeProvince = () => {
	// 清除城市数据
	formData.city_id = 0
	cities.value = []
	
	// 清除区县数据
	formData.district_id = 0
	districts.value = []
	formData.region = ''
	
	if (formData.province_id > 0) {
		getCityList(formData.province_id)
	}
}

// 选择城市
const changeCity = () => {
	formData.district_id = 0
	districts.value = []
	formData.region = ''
	if (formData.city_id > 0) {
		getDistrictList(formData.city_id)
	}
}

// 选择区县
const changeDistrict = () => {
	// 获取省份名称
	const province:any = provinces.value.find((item:any) => item.value == formData.province_id)
	// 获取城市名称
	const city:any = cities.value.find((item:any) => item.value == formData.city_id)
	// 获取区县名称
	const district:any = districts.value.find((item:any) => item.value == formData.district_id)
	
	formData.region = province.text + '-' + city.text + '-' + district.text
}
// ------------- 编辑收货地址功能结束 -------------


	
// ------------- 删除收货地址功能开始 -------------
const deleteDeliveryAddress = (item:any) => {
	uni.showModal({
		content: '确定要删除该收货地址吗?',
		success: async (res) => {
			if (res.confirm) {
        		await reqDeleteUserDeliveryAddrAPI({ids: item.id})

				// 从数据中删除
				const index = userAddrList.value.findIndex((v:any) => v.id == item.id)
				userAddrList.value.splice(index, 1)

				// 判断当前删除的地址是否为选中的地址，是则需要删除持久化的数据
				const deliveryAddr = userStore.deliveryAddr
				if (item.id == deliveryAddr.id) {
					userStore.clearDeliveryAddr()
				}

				uni.showToast({
					title: '删除地址成功',
					duration: 1000
				})
			}
		}
	});
}
// ------------- 删除收货地址功能结束 -------------
</script>

<style scoped lang="scss">
.address-container {
    background-color: #FAF5F5;
    height: 100vh;
    padding: 20rpx 10rpx 0 10rpx;
    .address-item {
        display: flex;
        align-items: center;

        background-color: #fff;
        border-radius: 5rpx;
        padding: 20rpx 20rpx 20rpx 10rpx;
        margin-bottom: 20rpx;
        .left {
            width: 60rpx;
            height: 60rpx;
            line-height: 60rpx;
            text-align: center;
            .icon {
                font-size: 50rpx;
                color: #008000;
            }
        }
        .middle {
            flex: 1;
            padding-right: 20rpx;
            .top {
                display: flex;
                justify-content: space-between;
                .top-right {
                    font-size: 24rpx;
                    padding: 0 10rpx;
                    color: #008000;
                    background-color: #95F595;
                }
            }
            .bottom {
                margin-top: 10rpx;
                color: #ccc;
                font-size: 24rpx;
            }
        }
        .right {
            width: 120rpx;
            display: flex;
            justify-content: space-between;
            .icon {
                font-size: 40rpx;
                color: #ccc;
                &:last-child {
                    color: #CD0011;
                }
            }
			.icon-bianji {
				color: #008000;
			}
        }
    }

    .address-btn-wrap {
        position: fixed;
        bottom: 30rpx;
        left: 0;

        display: flex;
        justify-content: center;

        width: 100%;
        
        .address-btn {
            background-color: #008000;
            color: #fff;
            width: 80%;
        }

    }

    .delivery-addr {
        padding: 40rpx 20rpx 0 20rpx;

        .region-box {
            display: flex;
            justify-content: space-between;
            .region-item {
                width: 32%;
            }
        }
    }

    .delivery-addr-btn-box {
        display: flex;
        justify-content: space-evenly;
        padding-bottom: 20rpx;
        .delivery-addr-btn {
            width: 45%;
        }
    }
}
</style>